//
//  UIButton+Countdown.swift
//  chat
//
//  Created by 崔世强 on 2018/11/1.
//  Copyright © 2018 崔世强. All rights reserved.
//

import Foundation
import UIKit


extension UIButton {
    
    
    /// 添加一个倒计时，便于实现类似短信验证码按钮的功能
    ///
    /// - Parameters:
    ///   - time: 倒计时时长
    ///   - tick: 每次步进时长
    ///   - onTick: 步进触发事件
    ///   - onFinish: 倒计时完成触发
    func startCountDown(time:TimeInterval,tick:TimeInterval,onTick:((_ timer:Timer,_ times:Int,_ remain:TimeInterval) -> Void)? ,onFinish: ((_ times:Int) -> Void)? ) {
        var tickTimes = 0 //当前第几次触发
        _ = Timer.scheduledTimer(withTimeInterval: tick, repeats: true) { timer in
            tickTimes += 1
            let spendTime = tick * TimeInterval(tickTimes)
            if spendTime >= time {
                timer.invalidate()
                onFinish?(tickTimes)
            } else {
                onTick?(timer,tickTimes,time - spendTime)
            }
        }
    }
}
